package org.wishwork.api.token.refresh;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.token.get.ResponseToken;
import org.wishwork.cache.DefaultMemoryCacheOperator;
import org.wishwork.constant.Constants;
import org.wishwork.context.Context;
import org.wishwork.exception.ExceptionEnum;
import org.wishwork.exception.JSTException;
import org.wishwork.helper.JuShuiTanHelper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 刷新token
 * @author: WangYX
 * @create: 2022-04-02 13:46
 * @Version: 1.0.0
 **/
public class RefreshToken {

    private static final Logger log = LoggerFactory.getLogger(RefreshToken.class);

    private Context context;

    public RefreshToken(Context context) {
        this.context = context;
    }

    /**
     * 刷新token
     *
     * @param refreshToken
     * @return
     * @throws IOException
     */
    public String refreshToken(String refreshToken) throws IOException {
        if (StrUtil.isBlank(refreshToken)) {
            throw new JSTException(ExceptionEnum.USER_ERROR_A0410);
        }
        Map<String, String> params = new HashMap<>();
        params.put("app_key", context.properties().getAppKey());
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("grant_type", "refresh_token");
        params.put("charset", "utf-8");
        params.put("refresh_token", refreshToken);
        params.put("scope", "all");
        params.put("sign", JuShuiTanHelper.signTopRequest(params, context.properties().getAppSecret(), JuShuiTanHelper.SIGN_METHOD_MD5));

        //获取accessToken的地址
        String url = context.properties().getOpenWebUrl() + "/openWeb/auth/refreshToken";
        String query = JuShuiTanHelper.buildQuery(params);
        String result = HttpUtil.post(url, query);

        JSONObject json = JSONObject.parseObject(result);
        //接口请求返回的状态
        String resCode = json.getString("code");
        if (Constants.SUCCESS.equals(resCode)) {
            String data = json.getString("data");
            ResponseToken responseToken = JSON.parseObject(data, ResponseToken.class);

            //token存到本地缓存中
            DefaultMemoryCacheOperator.instance().put(Constants.TOKEN, responseToken, responseToken.getExpiresIn() - 3600);

            return responseToken.getAccessToken();
        } else {
            log.error("获取聚水潭AccessToken异常：{}", json.toJSONString());
            throw new JSTException(ExceptionEnum.SERVICE_ERROR_C0001);
        }
    }


}
